<template>
  <view class="approver-page" v-if="visible">
    <!-- 自定义导航栏 -->
    <view class="page-header">
      <view class="nav-back" @click="handleBack">
        <u-icon name="arrow-left" size="20" color="#1a3582"></u-icon>
      </view>
      <text class="nav-title">选择审批人员</text>
      <view class="nav-placeholder"></view>
    </view>

    <view class="page-content">
      <!-- 审批说明 -->
      <!-- <view class="selector-info">
        <view class="info-card">
          <u-icon
            name="info-circle"
            :color="approvalAction === 'reject' ? '#ef4444' : '#1e40af'"
            size="16"
          ></u-icon>
          <view class="info-text">
            <text v-if="approvalAction === 'reject'" class="info-desc warning">
              拒绝操作不需要选择审批人员，请直接填写拒绝理由
            </text>
            <text v-else-if="approverList.length === 1" class="info-desc">
              系统已自动选择审批人员，无需手动选择
            </text>
            <text v-else class="info-desc"> 请选择审批人员，选择顺序即为审批顺序 </text>
          </view>
        </view>
      </view> -->

      <!-- 单人审批：自动选中 -->
      <view v-if="approverList.length === 1" class="single-approver">
        <view class="approver-card">
          <text class="approver-icon">👤</text>
          <view class="approver-details">
            <text class="approver-name">{{ approverList[0].label }}</text>
            <text class="approver-dept">{{ approverList[0].deptName || '未分配部门' }}</text>
          </view>
          <view class="auto-selected-badge">
            <text>已自动选择</text>
          </view>
        </view>
      </view>

      <!-- 多人审批：左右列表 -->
      <view v-else class="multi-approver">
        <view class="module-title">选择{{ currentNextStepName }}</view>
        <!-- 搜索框 -->
        <view class="search-box">
          <view class="search-input-wrapper">
            <u-icon name="search" size="18" color="#9ca3af"></u-icon>
            <input
              v-model="searchKeyword"
              class="search-input"
              placeholder="搜索姓名、部门或职位"
              placeholder-style="color: #9ca3af; font-size: 26rpx;"
              @input="handleSearchInput"
            />
            <view v-if="searchKeyword" class="clear-search" @click.stop="clearSearch">
              <u-icon name="close-circle-fill" size="20" color="#9ca3af"></u-icon>
            </view>
          </view>
        </view>
        <view class="approver-lists">
          <!-- 左侧：可选人员 -->
          <view class="approver-list left-list">
            <view class="list-header">
              <text class="list-title">可选人员</text>
              <text class="list-count"
                >({{ filteredApproverList.length }}/{{ approverList.length }})</text
              >
            </view>
            <scroll-view class="list-content" scroll-y>
              <view
                v-for="approver in filteredApproverList"
                :key="approver.key"
                class="approver-item"
                :class="{ selected: isSelected(approver.key), disabled: isSelected(approver.key) }"
                @click="selectApprover(approver.key)"
              >
                <view class="approver-info">
                  <text class="approver-name">{{ approver.label }}</text>
                  <text class="approver-dept">{{ approver.deptName || '未分配部门' }}</text>
                </view>
                <view class="check-icon" v-if="isSelected(approver.key)">
                  <text>✓</text>
                </view>
              </view>
              <view v-if="filteredApproverList.length === 0" class="empty-state">
                <text>未找到匹配的人员</text>
              </view>
            </scroll-view>
          </view>

          <!-- 右侧：已选人员 -->
          <view class="approver-list right-list">
            <view class="list-header">
              <text class="list-title">已选人员</text>
              <text class="list-count">({{ selectedList.length }})</text>
            </view>
            <scroll-view class="list-content" scroll-y>
              <view
                v-for="(approverId, index) in selectedList"
                :key="approverId"
                class="approver-item selected"
              >
                <view class="order-number">{{ index + 1 }}</view>
                <view class="approver-info">
                  <text class="approver-name">{{ getApproverName(approverId) }}</text>
                  <text class="approver-dept">{{ getApproverDept(approverId) }}</text>
                </view>
                <view class="remove-btn" @click.stop="removeApprover(approverId)">
                  <text>×</text>
                </view>
              </view>
              <view v-if="selectedList.length === 0" class="empty-state">
                <text>暂无已选人员</text>
              </view>
            </scroll-view>
          </view>
        </view>

        <!-- 审批顺序预览 -->
        <!-- <view class="order-preview" v-if="selectedList.length > 0">
          <text class="preview-title">审批顺序：</text>
          <view class="order-tags">
            <view
              v-for="(approverId, index) in selectedList"
              :key="approverId"
              class="order-tag"
              :style="{ backgroundColor: getOrderColor(index) }"
            >
              <text>{{ index + 1 }}. {{ getApproverName(approverId) }}</text>
            </view>
          </view>
        </view> -->
      </view>

      <!-- 科室办理：选择其他科室 -->
      <view
        class="multi-approver"
        v-if="props.deptManageApprovers && props.deptManageApprovers.length > 0"
      >
        <view class="module-title">选择其他科室协办</view>
        <!-- 搜索框 -->
        <view class="search-box">
          <view class="search-input-wrapper">
            <u-icon name="search" size="18" color="#9ca3af"></u-icon>
            <input
              v-model="searchDeptManageKeyword"
              class="search-input"
              placeholder="搜索姓名、部门或职位"
              placeholder-style="color: #9ca3af; font-size: 26rpx;"
              @input="handleDeptManageSearchInput"
            />
            <view
              v-if="searchDeptManageKeyword"
              class="clear-search"
              @click.stop="clearDeptManageSearch"
            >
              <u-icon name="close-circle-fill" size="20" color="#9ca3af"></u-icon>
            </view>
          </view>
        </view>
        <view class="approver-lists">
          <!-- 左侧：可选人员 -->
          <view class="approver-list left-list">
            <view class="list-header">
              <text class="list-title">可选人员</text>
              <text class="list-count"
                >({{ filteredDeptManageApproverList.length }}/{{
                  props.deptManageApprovers?.length || 0
                }})</text
              >
            </view>
            <scroll-view class="list-content" scroll-y>
              <view
                v-for="approver in filteredDeptManageApproverList"
                :key="approver.key"
                class="approver-item"
                :class="{
                  selected: isDeptManageSelected(approver.key),
                  disabled: isDeptManageSelected(approver.key),
                }"
                @click="selectDeptManageApprover(approver.key)"
              >
                <view class="approver-info">
                  <text class="approver-name">{{ approver.label }}</text>
                  <text class="approver-dept">{{ approver.deptName || '未分配部门' }}</text>
                </view>
                <view class="check-icon" v-if="isDeptManageSelected(approver.key)">
                  <text>✓</text>
                </view>
              </view>
              <view v-if="filteredDeptManageApproverList.length === 0" class="empty-state">
                <text>未找到匹配的人员</text>
              </view>
            </scroll-view>
          </view>

          <!-- 右侧：已选人员 -->
          <view class="approver-list right-list">
            <view class="list-header">
              <text class="list-title">已选人员</text>
              <text class="list-count">({{ selectedDeptManageList.length }})</text>
            </view>
            <scroll-view class="list-content" scroll-y>
              <view
                v-for="(approverId, index) in selectedDeptManageList"
                :key="approverId"
                class="approver-item selected"
              >
                <view class="order-number">{{ index + 1 }}</view>
                <view class="approver-info">
                  <text class="approver-name">{{ getDeptManageApproverName(approverId) }}</text>
                  <text class="approver-dept">{{ getDeptManageApproverDept(approverId) }}</text>
                </view>
                <view class="remove-btn" @click.stop="removeDeptManageApprover(approverId)">
                  <text>×</text>
                </view>
              </view>
              <view v-if="selectedDeptManageList.length === 0" class="empty-state">
                <text>暂无已选人员</text>
              </view>
            </scroll-view>
          </view>
        </view>
      </view>

      <!-- 审批模块（操作、退回步骤、意见、手写意见）- 文秘步骤不显示 -->
      <view v-if="!props.currentStepName?.includes('文秘')" class="approval-form">
        <view class="form-content">
          <view class="module-title">审批</view>

          <!-- 审批操作 -->
          <view class="form-item">
            <text class="form-label required">审批操作</text>
            <view class="radio-group">
              <view class="radio-item" @click="approvalAction = 'approve'">
                <view class="radio" :class="{ checked: approvalAction === 'approve' }">
                  <view v-if="approvalAction === 'approve'" class="radio-dot"></view>
                </view>
                <text class="radio-label">同意</text>
              </view>
              <view class="radio-item" @click="approvalAction = 'reject'">
                <view class="radio" :class="{ checked: approvalAction === 'reject' }">
                  <view v-if="approvalAction === 'reject'" class="radio-dot"></view>
                </view>
                <text class="radio-label">拒绝</text>
              </view>
            </view>
          </view>

          <!-- 退回步骤选择（科室办理且拒绝时显示） -->
          <view class="form-item" v-if="showRejectStepSelector">
            <text class="form-label required">退回步骤</text>
            <view class="step-button-group">
              <view
                v-for="(option, index) in rejectOptions"
                :key="index"
                class="step-button"
                :class="{ active: rejectNextStep === option.value }"
                @click="rejectNextStep = option.value"
              >
                <text>{{ option.label }}</text>
              </view>
            </view>
          </view>

          <!-- 审批意见（文本输入） -->
          <view class="form-item">
            <text class="form-label">审批意见</text>
            <!-- 文本输入 (无签名时显示) -->
            <textarea
              v-if="!signaturePath"
              v-model="approvalOpinion"
              class="opinion-input"
              placeholder="请输入审批意见"
              :maxlength="200"
              auto-height
            />
            <!-- <view v-if="!signaturePath" class="word-count">
              <text>{{ approvalOpinion.length }}/200</text>
            </view> -->
          </view>

          <!-- 手写意见（可选） -->
          <view class="form-item">
            <view class="signature-header">
              <text class="form-label optional">手写意见 (可选)</text>
              <view class="signature-btn" @click="openSignaturePad">
                <u-icon name="edit-pen" size="16" color="#1a3582"></u-icon>
                <text>{{ signaturePath ? '重新签名' : '点击签名' }}</text>
              </view>
            </view>

            <view class="signature-area">
              <view v-if="signaturePath" class="signature-preview-box">
                <image
                  :src="signaturePath"
                  mode="aspectFit"
                  class="signature-img"
                  @click="previewSignature"
                />
                <view class="clear-signature" @click.stop="clearStoredSignature">
                  <u-icon name="close-circle-fill" size="24" color="#ef4444"></u-icon>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部操作按钮 -->
    <view class="page-footer">
      <view class="footer-btn cancel" @click="handleBack">
        <text>取消</text>
      </view>
      <view class="footer-btn confirm" :class="{ disabled: !canConfirm }" @click="handleConfirm">
        <text>确认选择</text>
      </view>
    </view>
  </view>

  <!-- 手写签名弹窗 -->
  <u-popup
    :show="showSignature"
    mode="center"
    width="100%"
    height="100%"
    :border-radius="0"
    :mask-close-able="false"
    @close="closeSignaturePad"
  >
    <view class="signature-popup-container">
      <view class="popup-header">
        <text class="title">请在下方区域手写审批意见</text>
        <u-icon name="close" size="32" @click="closeSignaturePad"></u-icon>
      </view>

      <view class="signature-content">
        <l-signature
          ref="signatureRef"
          :penColor="'#000000'"
          :penSize="5"
          :openSmooth="true"
          disableScroll
          landscape
        ></l-signature>
      </view>

      <view class="popup-footer">
        <view class="btn reset" @click="handleSignatureClear">
          <u-icon name="reload" size="28"></u-icon>
          <text>重写</text>
        </view>
        <view class="btn confirm" @click="handleSignatureConfirm">
          <u-icon name="checkmark" size="28"></u-icon>
          <text>确认使用</text>
        </view>
      </view>
    </view>
  </u-popup>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { uploadFile } from '@/Api/request'

// Props
const props = defineProps<{
  visible: boolean
  approverList: Array<{
    key: number
    label: string
    deptName?: string
    job?: string
  }>
  deptManageApprovers?: Array<{
    key: number
    label: string
    deptName?: string
    job?: string
  }>
  currentStepName?: string
  currentNextStepName?: string
  rejectRecords?: Array<{
    nextStep: string
    nextStepName?: string
  }>
  isDeptManageTransfer?: boolean
}>()

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  confirm: [
    approvers: Array<{ id: number; name: string }>,
    opinion: string,
    action: string,
    signature: string, // 新增签名参数
    rejectNextStep?: string, // 退回步骤
    deptManageApprovers?: Array<{ id: number; name: string }>, // 选择其他科室办理的人员
  ]
  close: []
}>()

// 已选人员列表（本科室）
const selectedList = ref<number[]>([])

// 已选人员列表（其他科室）
const selectedDeptManageList = ref<number[]>([])

// 搜索关键词（本科室）
const searchKeyword = ref('')

// 搜索关键词（其他科室）
const searchDeptManageKeyword = ref('')

// 审批表单数据
const approvalAction = ref('approve')
const approvalOpinion = ref('') // 文字意见
const signaturePath = ref('') // 签名图片路径
const showSignature = ref(false)
const signatureRef = ref<any>(null)
const rejectNextStep = ref('') // 退回步骤

// 是否显示退回步骤选择器
const showRejectStepSelector = computed(() => {
  return (
    approvalAction.value === 'reject' &&
    props.currentStepName?.includes('科室办理') &&
    rejectOptions.value.length > 0
  )
})

// 退回选项列表
const rejectOptions = computed(() => {
  return (props.rejectRecords || []).map((r) => ({
    label: r.nextStepName || r.nextStep,
    value: r.nextStep,
  }))
})

// 过滤后的可选人员列表（本科室）
const filteredApproverList = computed(() => {
  if (!searchKeyword.value.trim()) {
    return props.approverList
  }
  const keyword = searchKeyword.value.trim().toLowerCase()
  return props.approverList.filter((approver) => {
    const name = approver.label?.toLowerCase() || ''
    const dept = approver.deptName?.toLowerCase() || ''
    const job = approver.job?.toLowerCase() || ''
    return name.includes(keyword) || dept.includes(keyword) || job.includes(keyword)
  })
})

// 过滤后的可选人员列表（其他科室）
const filteredDeptManageApproverList = computed(() => {
  const deptManageList = props.deptManageApprovers || []
  if (!searchDeptManageKeyword.value.trim()) {
    return deptManageList
  }
  const keyword = searchDeptManageKeyword.value.trim().toLowerCase()
  return deptManageList.filter((approver) => {
    const name = approver.label?.toLowerCase() || ''
    const dept = approver.deptName?.toLowerCase() || ''
    const job = approver.job?.toLowerCase() || ''
    return name.includes(keyword) || dept.includes(keyword) || job.includes(keyword)
  })
})

// 监听visible变化，初始化数据
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      // 自动选择单人情况
      if (props.approverList.length === 1) {
        selectedList.value = [props.approverList[0].key]
      } else {
        selectedList.value = []
      }
      // 重置审批表单
      approvalAction.value = 'approve'
      approvalOpinion.value = ''
      signaturePath.value = ''
      rejectNextStep.value = ''
      // 重置搜索关键词
      searchKeyword.value = ''
      searchDeptManageKeyword.value = ''
      // 重置已选人员列表
      selectedDeptManageList.value = []
      // 如果有退回选项，自动选中第一个
      if (rejectOptions.value.length > 0) {
        rejectNextStep.value = rejectOptions.value[0].value
      }
      changeOpinion()
    }
  },
  { immediate: true },
)

// 监听审批操作变化，重新生成意见
watch(approvalAction, (newAction) => {
  // 如果选择拒绝，清空已选人员
  if (newAction === 'reject') {
    selectedList.value = []
    selectedDeptManageList.value = []
    // 如果有退回选项，自动选中第一个
    if (rejectOptions.value.length > 0 && !rejectNextStep.value) {
      rejectNextStep.value = rejectOptions.value[0].value
    }
  }
  changeOpinion()
})

// 是否已选中
const isSelected = (approverId: number): boolean => {
  return selectedList.value.includes(approverId)
}

// 选择审批人员
const selectApprover = (approverId: number) => {
  if (!isSelected(approverId)) {
    selectedList.value.push(approverId)
    changeOpinion()
  }
}

// 移除审批人员
const removeApprover = (approverId: number) => {
  const index = selectedList.value.indexOf(approverId)
  if (index > -1) {
    selectedList.value.splice(index, 1)
    changeOpinion()
  }
}

// 获取审批人姓名
const getApproverName = (approverId: number): string => {
  const approver = props.approverList.find((a) => a.key === approverId)
  return approver?.label || '未知'
}

// 获取审批人部门
const getApproverDept = (approverId: number): string => {
  const approver = props.approverList.find((a) => a.key === approverId)
  return approver?.deptName || '未分配部门'
}

// 是否已选中（其他科室）
const isDeptManageSelected = (approverId: number): boolean => {
  return selectedDeptManageList.value.includes(approverId)
}

// 选择其他科室审批人员
const selectDeptManageApprover = (approverId: number) => {
  if (!isDeptManageSelected(approverId)) {
    selectedDeptManageList.value.push(approverId)
    changeOpinion()
  }
}

// 移除其他科室审批人员
const removeDeptManageApprover = (approverId: number) => {
  const index = selectedDeptManageList.value.indexOf(approverId)
  if (index > -1) {
    selectedDeptManageList.value.splice(index, 1)
    changeOpinion()
  }
}

// 获取其他科室审批人姓名
const getDeptManageApproverName = (approverId: number): string => {
  const approver = props.deptManageApprovers?.find((a) => a.key === approverId)
  return approver?.label || '未知'
}

// 获取其他科室审批人部门
const getDeptManageApproverDept = (approverId: number): string => {
  const approver = props.deptManageApprovers?.find((a) => a.key === approverId)
  return approver?.deptName || '未分配部门'
}

// 获取顺序颜色
const getOrderColor = (index: number): string => {
  const colors = ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6']
  return colors[index % colors.length]
}

// 根据选择的人员和步骤动态生成审批意见
const changeOpinion = () => {
  // 文秘步骤自动填写"-"
  if (props.currentStepName?.includes('文秘')) {
    approvalOpinion.value = '-'
    return
  }

  // 如果是同意，办公室主任步骤，且选择了审批人员，自动生成意见
  if (
    approvalAction.value === 'approve' &&
    props.currentStepName?.includes('办公室主任') &&
    selectedList.value.length > 0
  ) {
    // 获取选中人员的姓名+职位列表
    const approverNames = selectedList.value.map((id: number) => {
      const a: any = props.approverList.find((x: any) => x.key === id)
      return a?.label + a?.job
    })
    // 生成默认意见："请{姓名1}，{姓名2}阅示。"
    const defaultOpinion = `请${approverNames.join('，')}阅示。`

    // 如果当前没有手写签名，且意见为空或者是之前自动生成的格式，则更新为新的默认意见
    if (!signaturePath.value) {
      // 检查当前意见是否是之前自动生成的格式（以"请"开头，以"阅示。"结尾）
      const isAutoGenerated =
        approvalOpinion.value.startsWith('请') && approvalOpinion.value.endsWith('阅示。')
      if (!approvalOpinion.value || isAutoGenerated) {
        approvalOpinion.value = defaultOpinion
      }
    }
    return
  }
  approvalOpinion.value = ''
  return
}

// 是否可以确认
const canConfirm = computed(() => {
  const hasApprovers = selectedList.value.length > 0
  const hasDeptManageApprovers = selectedDeptManageList.value.length > 0
  const isWenshu = props.currentStepName?.includes('文秘')
  const isApprove = approvalAction.value === 'approve'

  // 检查是否有意见（文字或签名）
  const hasOpinion = !!approvalOpinion.value.trim() || !!signaturePath.value

  // 拒绝操作：不需要选择审批人员，但必须填写意见
  if (!isApprove) {
    // 如果是科室办理且拒绝，必须选择退回步骤
    if (showRejectStepSelector.value && !rejectNextStep.value) {
      return false
    }
    return hasOpinion
  }

  // 同意操作：必须选择审批人员（本科室或其他科室至少选一个），且必须填写意见或签名
  return (hasApprovers || hasDeptManageApprovers) && hasOpinion
})

// 返回上一页
const handleBack = () => {
  emit('update:visible', false)
  emit('close')
}

// 确认选择
const handleConfirm = () => {
  const isApprove = approvalAction.value === 'approve'

  // 同意操作：必须选择审批人员（本科室或其他科室至少选一个）
  if (isApprove && selectedList.value.length === 0 && selectedDeptManageList.value.length === 0) {
    uni.showToast({
      title: '请至少选择一个审批人员',
      icon: 'none',
    })
    return
  }

  // 检查意见或签名是否为空
  const hasOpinion = !!approvalOpinion.value.trim() || !!signaturePath.value
  if (!hasOpinion) {
    uni.showToast({
      title: '请输入审批意见或手写签名',
      icon: 'none',
    })
    return
  }

  // 如果是科室办理且拒绝，必须选择退回步骤
  if (!isApprove && showRejectStepSelector.value && !rejectNextStep.value) {
    uni.showToast({
      title: '请选择退回步骤',
      icon: 'none',
    })
    return
  }

  // 构造审批人员列表（拒绝操作时传空数组）
  const approvers = isApprove
    ? selectedList.value.map((id) => {
        const approver = props.approverList.find((a) => a.key === id)
        return {
          id,
          name: approver?.label || '',
        }
      })
    : []

  // 构造其他科室办理人员列表
  const deptManageApprovers = isApprove
    ? selectedDeptManageList.value.map((id) => {
        const approver = props.deptManageApprovers?.find((a) => a.key === id)
        return {
          id,
          name: approver?.label || '',
        }
      })
    : []

  const opinion = approvalOpinion.value || ''
  // 传递文字意见、签名路径、退回步骤和其他科室办理人员
  emit(
    'confirm',
    approvers,
    opinion,
    approvalAction.value,
    signaturePath.value,
    rejectNextStep.value || undefined,
    deptManageApprovers.length > 0 ? deptManageApprovers : undefined,
  )
  emit('update:visible', false)
  emit('close')
}

// 打开签名板
const openSignaturePad = () => {
  showSignature.value = true
  setTimeout(() => {
    // 延时初始化
  }, 300)
}

// 关闭签名板
const closeSignaturePad = () => {
  showSignature.value = false
}

// 清除当前画布
const handleSignatureClear = () => {
  if (signatureRef.value) {
    signatureRef.value.clear()
  }
}

// 清除已保存的签名
const clearStoredSignature = () => {
  signaturePath.value = ''
}

// 预览签名
const previewSignature = () => {
  if (signaturePath.value) {
    uni.previewImage({
      urls: [signaturePath.value],
    })
  }
}

// 确认签名
const handleSignatureConfirm = () => {
  if (signatureRef.value) {
    signatureRef.value.canvasToTempFilePath({
      success: (res: any) => {
        if (res.isEmpty) {
          uni.showToast({ title: '请先签名', icon: 'none' })
          return
        }

        // 上传签名图片
        uni.showLoading({ title: '正在保存签名...' })

        uploadFile({
          url: '/system/file/upload',
          filePath: res.tempFilePath,
          name: 'file',
        })
          .then((response: any) => {
            // 解析返回结果，获取图片URL
            const fileUrl = response.data?.url

            if (fileUrl) {
              // 保存服务器返回的图片URL
              signaturePath.value = fileUrl
              // 清空文字意见
              approvalOpinion.value = ''
              showSignature.value = false
              uni.showToast({ title: '签名已保存', icon: 'success' })
            } else {
              throw new Error('未获取到图片地址')
            }
          })
          .catch((err) => {
            console.error('签名上传失败', err)
            uni.showToast({
              title: '签名保存失败，请重试',
              icon: 'none',
            })
          })
          .finally(() => {
            uni.hideLoading()
          })
      },
      fail: (err: any) => {
        console.error('签名生成失败', err)
        uni.showToast({ title: '签名生成失败', icon: 'none' })
      },
    })
  }
}

// 处理搜索输入
const handleSearchInput = () => {
  // 搜索逻辑已在 computed 中处理
}

// 清空搜索
const clearSearch = () => {
  searchKeyword.value = ''
}

// 处理其他科室搜索输入
const handleDeptManageSearchInput = () => {
  // 搜索逻辑已在 computed 中处理
}

// 清空其他科室搜索
const clearDeptManageSearch = () => {
  searchDeptManageKeyword.value = ''
}
</script>

<style lang="scss" scoped>
.approver-page {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  min-height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
  padding-bottom: 140rpx; // 为底部按钮留出空间
  z-index: 1000;

  .page-header {
    background: white;
    padding: 44px 24rpx 24rpx;
    height: 132rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1rpx solid #e5e7eb;
    position: sticky;
    top: 0;
    z-index: 100;

    .nav-back {
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .nav-title {
      font-size: 36rpx;
      font-weight: bold;
      color: #1a3582;
      flex: 1;
      text-align: center;
    }

    .nav-placeholder {
      width: 60rpx;
    }
  }

  .page-content {
    flex: 1;
    overflow-y: auto;
    background: white;

    .selector-info {
      padding: 12rpx 32rpx;
      background: #f0f9ff;
      flex-shrink: 0;
      margin-top: 0;

      .info-card {
        display: flex;
        gap: 16rpx;

        .info-icon {
          font-size: 32rpx;
          flex-shrink: 0;
        }

        .info-text {
          flex: 1;

          .info-desc {
            font-size: 26rpx;
            color: #1e40af;
            line-height: 1.5;

            &.warning {
              color: #ef4444;
              font-weight: 500;
            }
          }
        }
      }
    }

    .single-approver {
      flex: 1;
      padding: 32rpx;
      overflow-y: auto;

      .approver-card {
        background: #f9fafb;
        border-radius: 12rpx;
        padding: 32rpx;
        display: flex;
        align-items: center;
        gap: 24rpx;
        border: 2rpx solid #3b82f6;

        .approver-icon {
          font-size: 64rpx;
        }

        .approver-details {
          flex: 1;

          .approver-name {
            display: block;
            font-size: 32rpx;
            font-weight: 600;
            color: #1a3582;
            margin-bottom: 8rpx;
          }

          .approver-dept {
            display: block;
            font-size: 24rpx;
            color: #6b7280;
          }
        }

        .auto-selected-badge {
          padding: 12rpx 24rpx;
          background: #10b981;
          border-radius: 20rpx;

          text {
            font-size: 22rpx;
            color: white;
            font-weight: 500;
          }
        }
      }
    }

    // 统一的模块标题样式
    .module-title {
      font-size: 30rpx;
      font-weight: 600;
      color: #1a3582;
      padding: 24rpx 32rpx;
      background: linear-gradient(135deg, #ecf5ff 0%, #f0f9ff 100%);
      border-left: 6rpx solid #1a3582;
      margin-bottom: 24rpx;
      display: flex;
      align-items: center;
      position: relative;
      border-radius: 0 8rpx 8rpx 0;
      box-shadow: 0 2rpx 8rpx rgba(26, 53, 130, 0.08);

      .required-mark {
        color: #ef4444;
        margin-left: 4rpx;
        font-size: 30rpx;
      }

      .optional-mark {
        color: #6b7280;
        margin-left: 8rpx;
        font-size: 24rpx;
        font-weight: 400;
      }

      &.optional {
        border-left-color: #9ca3af;
        background: linear-gradient(135deg, #f9fafb 0%, #f3f4f6 100%);
      }
    }

    .multi-approver {
      flex: 1;
      padding: 24rpx 32rpx;

      .module-title {
        margin: 0 -32rpx 24rpx -32rpx;
        border-radius: 0;
      }

      .search-box {
        margin-bottom: 20rpx;
        flex-shrink: 0;

        .search-input-wrapper {
          display: flex;
          align-items: center;
          background: #f9fafb;
          border: 1rpx solid #e5e7eb;
          border-radius: 12rpx;
          padding: 20rpx 24rpx;
          gap: 16rpx;

          .search-input {
            flex: 1;
            font-size: 26rpx;
            color: #374151;
            background: transparent;
            border: none;
            outline: none;
          }

          .clear-search {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 4rpx;
          }
        }
      }

      .approver-lists {
        display: flex;
        gap: 20rpx;
        height: 400rpx;

        .approver-list {
          flex: 1;
          border: 1rpx solid #e5e7eb;
          border-radius: 12rpx;
          overflow: hidden;
          display: flex;
          flex-direction: column;
          background: white;

          &.left-list {
            .list-header {
              background: #f9fafb;
            }
          }

          &.right-list {
            .list-header {
              background: #ecf5ff;
            }
          }

          .list-header {
            padding: 16rpx 24rpx;
            border-bottom: 1rpx solid #e5e7eb;
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-shrink: 0;

            .list-title {
              font-size: 26rpx;
              font-weight: 600;
              color: #374151;
            }

            .list-count {
              font-size: 22rpx;
              color: #9ca3af;
              background: #e5e7eb;
              padding: 4rpx 12rpx;
              border-radius: 12rpx;
            }
          }

          .list-content {
            flex: 1;
            height: 320rpx;

            .approver-item {
              display: flex;
              align-items: center;
              padding: 20rpx 24rpx;
              border-bottom: 1rpx solid #f3f4f6;

              &.selected {
                background: #ecf5ff;
              }

              &.disabled {
                opacity: 0.5;
              }

              .order-number {
                width: 40rpx;
                height: 40rpx;
                background: #3b82f6;
                color: white;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 22rpx;
                font-weight: bold;
                margin-right: 16rpx;
                flex-shrink: 0;
              }

              .approver-info {
                flex: 1;

                .approver-name {
                  display: block;
                  font-size: 26rpx;
                  color: #1a3582;
                  font-weight: 500;
                  margin-bottom: 6rpx;
                }

                .approver-dept {
                  display: block;
                  font-size: 22rpx;
                  color: #9ca3af;
                }
              }

              .check-icon {
                width: 40rpx;
                height: 40rpx;
                background: #10b981;
                color: white;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 24rpx;
                font-weight: bold;
                flex-shrink: 0;
              }

              .remove-btn {
                width: 40rpx;
                height: 40rpx;
                background: #ef4444;
                color: white;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 32rpx;
                flex-shrink: 0;
              }
            }

            .empty-state {
              height: 240rpx;
              display: flex;
              align-items: center;
              justify-content: center;

              text {
                font-size: 24rpx;
                color: #9ca3af;
              }
            }
          }
        }
      }

      .order-preview {
        margin-top: 24rpx;
        padding: 24rpx;
        background: #f9fafb;
        border-radius: 12rpx;

        .preview-title {
          display: block;
          font-size: 26rpx;
          font-weight: 600;
          color: #374151;
          margin-bottom: 16rpx;
        }

        .order-tags {
          display: flex;
          flex-wrap: wrap;
          gap: 12rpx;

          .order-tag {
            padding: 10rpx 20rpx;
            border-radius: 20rpx;
            color: white;

            text {
              font-size: 22rpx;
              font-weight: 500;
            }
          }
        }
      }
    }

    .approval-form {
      border-top: 1rpx solid #e5e7eb;
      background: #fafafa;

      .form-divider {
        padding: 16rpx 32rpx;
        font-size: 28rpx;
        font-weight: 600;
        color: #374151;
        border-bottom: 1rpx solid #e5e7eb;
        background: white;
      }

      .form-content {
        .form-item {
          padding: 12rpx 32rpx;

          &:last-child {
            margin-bottom: 0;
          }

          .module-title {
            margin: 0 -32rpx 24rpx -32rpx;
            border-radius: 0;
          }

          .form-label {
            display: block;
            font-size: 26rpx;
            color: #374151;
            margin-bottom: 12rpx;
            font-weight: 500;

            &.required::after {
              content: '*';
              color: #ef4444;
              margin-left: 4rpx;
            }

            &.optional {
              color: #6b7280;
            }
          }

          .radio-group {
            display: flex;
            gap: 32rpx;

            .radio-item {
              display: flex;
              align-items: center;
              gap: 12rpx;
              cursor: pointer;

              .radio {
                width: 32rpx;
                height: 32rpx;
                border: 2rpx solid #d1d5db;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                background: white;

                &.checked {
                  border-color: #3b82f6;
                  background: #3b82f6;
                }

                .radio-dot {
                  width: 12rpx;
                  height: 12rpx;
                  background: white;
                  border-radius: 50%;
                }
              }

              .radio-label {
                font-size: 26rpx;
                color: #374151;
              }
            }
          }

          .step-button-group {
            display: flex;
            gap: 24rpx;
            flex-wrap: wrap;

            .step-button {
              flex: 1;
              min-width: 200rpx;
              height: 88rpx;
              border: 2rpx solid #e5e7eb;
              border-radius: 12rpx;
              display: flex;
              align-items: center;
              justify-content: center;
              background: white;

              &.active {
                border-color: #1a3582;
                background: #ecf5ff;

                text {
                  color: #1a3582;
                  font-weight: 600;
                }
              }

              text {
                font-size: 26rpx;
                color: #6b7280;
              }
            }
          }

          .opinion-input {
            width: 100%;
            min-height: 120rpx;
            padding: 16rpx;
            border: 1rpx solid #d1d5db;
            border-radius: 8rpx;
            font-size: 26rpx;
            line-height: 1.5;
            background: white;
            box-sizing: border-box;
            margin-bottom: 16rpx;
          }

          .word-count {
            display: flex;
            justify-content: flex-end;
            margin-top: 8rpx;
            margin-bottom: 16rpx;

            text {
              font-size: 22rpx;
              color: #9ca3af;
            }
          }

          .signature-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 16rpx;
            width: 100%;

            .form-label {
              display: inline-block;
              margin-bottom: 0;
              flex-shrink: 0;
            }

            .signature-btn {
              display: flex;
              align-items: center;
              gap: 8rpx;
              padding: 12rpx 24rpx;
              background: #eff6ff;
              border-radius: 8rpx;
              border: 1rpx solid #dbeafe;
              flex-shrink: 0;

              text {
                font-size: 26rpx;
                color: #1a3582;
                font-weight: 500;
              }
            }
          }
          .signature-area {
            .signature-preview-box {
              width: 100%;
              height: 160rpx;
              border: 1rpx solid #e5e7eb;
              border-radius: 8rpx;
              background: white;
              position: relative;
              overflow: hidden;
              display: flex;
              align-items: center;
              justify-content: center;

              .signature-img {
                width: 100%;
                height: 100%;
              }

              .clear-signature {
                position: absolute;
                top: 8rpx;
                right: 8rpx;
                z-index: 10;
                padding: 8rpx;
              }
            }
          }
        }
      }
    }
  }

  .page-footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 24rpx 32rpx;
    padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
    border-top: 1rpx solid #e5e7eb;
    background: white;
    display: flex;
    gap: 24rpx;
    flex-shrink: 0;
    z-index: 99;

    .footer-btn {
      flex: 1;
      height: 88rpx;
      border-radius: 12rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
      font-weight: 500;

      &.cancel {
        background: #f3f4f6;
        color: #6b7280;
        border: 1rpx solid #d1d5db;
      }

      &.confirm {
        background: #1a3582;
        color: white;

        &.disabled {
          opacity: 0.5;
          background: #9ca3af;
        }
      }
    }
  }
}

.signature-popup-container {
  width: 100vh;
  height: 100vw;
  background: white;
  display: flex;
  flex-direction: column;

  position: absolute;
  top: 50%;
  left: 50%;

  transform: translate(-50%, -50%) rotate(90deg);
  transform-origin: center center;
  overflow: hidden;

  .popup-header {
    position: relative;
    z-index: 10;
    background: white;
    padding: 24rpx 32rpx 24rpx 44px;
    border-bottom: 1rpx solid #eee;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-shrink: 0;

    .title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .signature-content {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    z-index: 1;

    transform: rotate(-90deg);
    transform-origin: center center;

    /* 旋转后需要重新计算尺寸：旋转后的宽度 = 原高度，旋转后的高度 = 原宽度 */
    width: 100vw;
    height: 100vh;
    top: 50%;
    left: 50%;
    margin-left: -50vw;
    margin-top: -50vh;

    background: #f5f5f5;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;

    :deep(l-signature) {
      width: 100% !important;
      height: 100% !important;
    }
  }

  .popup-footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 10;
    background: white;
    padding: 24rpx 32rpx;
    border-top: 1rpx solid #eee;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    gap: 24rpx;
    width: 100%;

    .btn {
      flex: 1;
      max-width: 300rpx;
      height: 88rpx;
      border-radius: 44rpx;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
      gap: 12rpx;
      font-size: 28rpx;
      font-weight: 500;
      padding: 0 32rpx;

      &.reset {
        background: #f3f4f6;
        color: #666;
        border: 1rpx solid #e5e7eb;
      }

      &.confirm {
        background: #1a3582;
        color: white;
      }
    }
  }
}
</style>
